package com.lckj.android.shell.utils;

import android.annotation.TargetApi;
import android.os.Build;
import android.view.View;
import android.view.Window;

import androidx.annotation.ColorInt;

/**
 * @author lc. 2023-10-22 16:36
 */
public class StatusBarUtil {

    /**
     * 设置状态栏文字颜色为黑色
     *
     * @param window         window
     * @param statusBarColor 状态栏的颜色
     */
    @TargetApi(Build.VERSION_CODES.M)
    public static void setStatusBarLightMode(Window window, @ColorInt int statusBarColor) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }

        // Android 6.0 之后的原生方式
        setStatusBarLightModeOrigin(window, true);
        // 黑色字体设置成功
        setStatusBarColor(window, statusBarColor);
    }

    /**
     * 设置状态栏文字颜色为白色
     *
     * @param window         window
     * @param statusBarColor 状态栏的颜色
     */
    public static void setStatusBarDarkMode(Window window, @ColorInt int statusBarColor) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }

        // Android 6.0 之后的原生方式
        setStatusBarLightModeOrigin(window, false);
        setStatusBarColor(window, statusBarColor);
    }

    /**
     * 修改状态栏颜色，支持4.4以上版本
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public static void setStatusBarColor(Window window, @ColorInt int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.setStatusBarColor(color);
        }
    }


    /** 使用原生系统 API 来设置状态栏文字颜色 */
    private static void setStatusBarLightModeOrigin(Window window, boolean lightMode) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }
        View decorView = window.getDecorView();
        int originVisibility = decorView.getSystemUiVisibility();
        // 亮色模式，使用黑色文字
        if (lightMode && (originVisibility & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR) == 0) {
            originVisibility = originVisibility | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        }

        // 暗色模式，使用白色文字
        if (!lightMode && (originVisibility & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR) != 0) {
            originVisibility = originVisibility ^ View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        }

        decorView.setSystemUiVisibility(originVisibility);
    }
}
